package com.truthbean.jeetb.cms.sys.servlet;

import com.truthbean.jeetb.utils.ImageUtils;
import com.truthbean.jeetb.utils.StringUtils;

import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by TruthBean on 2016-10-09 17:38.
 */
@WebServlet("/image.jpg")
public class ImageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //返回的类型
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        String _code = "status-0";

        //获取参数
        String action = request.getParameter("action"); //0表示生成二维码，1表示将图片加水印，2表示合成图片
        if (action != null && StringUtils.isNumber(action.trim())) {
            _code = "action-" + action.trim();
        }

        //0 表示纯数字，1表示字母与数字混搭, 2表示纯汉字，3表示简单数学公式
        String status = request.getParameter("status");
        if (status != null && StringUtils.isNumber(status.trim())) {
            _code = "status-" + status.trim();
        }

        //合成图片
        BufferedImage image = ImageUtils.drawImage(request, _code);
        //通过response将图片输出
        ServletOutputStream responseOutputStream = response.getOutputStream();
        ImageIO.write(image, "JPEG", responseOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}
